import sys
import re
from collections import defaultdict

def parse_time_to_ms(time_str):
    """
    将时间字符串（带单位）统一转换为毫秒（ms）
    支持单位：us, ms, s
    """
    if time_str.endswith('us'):
        value = float(time_str[:-2])
        return value / 1000.0  # 微秒 -> 毫秒
    elif time_str.endswith('ms'):
        value = float(time_str[:-2])
        return value  # 毫秒保持不变
    elif time_str.endswith('s'):
        value = float(time_str[:-1])
        return value * 1000.0  # 秒 -> 毫秒
    else:
        raise ValueError(f"Unknown time unit in '{time_str}'")

def parse_file(filename):
    """
    解析单个文件，提取所有 Name -> (P50, P99) 的值
    返回：列表，每个元素是一个 dict
    """
    results = []
    with open(filename, 'r') as f:
        lines = f.readlines()

    current_result = {}
    for line in lines:
        # 匹配数据行
        match = re.match(r'\|\s*(.*?)\s*\|\s*([\d\.]+\s*(?:us|ms|s))\s*\|\s*([\d\.]+\s*(?:us|ms|s))\s*\|', line)
        if match:
            name = match.group(1)
            p50_str = match.group(2).replace(' ', '')
            p99_str = match.group(3).replace(' ', '')
            p50 = parse_time_to_ms(p50_str)
            p99 = parse_time_to_ms(p99_str)
            current_result[name] = (p50, p99)
        elif line.strip() == '' and current_result:
            # 空行表示一组结束
            results.append(current_result)
            current_result = {}

    # 最后一组
    if current_result:
        results.append(current_result)

    return results

def average_results(results_list):
    """
    对多次结果求平均
    """
    avg_result = defaultdict(lambda: [0.0, 0.0])
    count = len(results_list)

    for result in results_list:
        for name, (p50, p99) in result.items():
            avg_result[name][0] += p50
            avg_result[name][1] += p99

    for name in avg_result:
        avg_result[name][0] /= count
        avg_result[name][1] /= count

    return avg_result

def write_output(avg_result, output_file):
    """
    写入最终输出文件
    """
    with open(output_file, 'w') as f:
        f.write("+---------------------------+---------------------------+---------------------------+\n")
        f.write("| Name                      | P50 (ms)                  | P99 (ms)                  |\n")
        f.write("+---------------------------+---------------------------+---------------------------+\n")
        for name in sorted(avg_result.keys()):
            p50, p99 = avg_result[name]
            f.write(f"| {name:<25} | {p50:.3f} ms{(27 - len(f'{p50:.3f} ms')) * ' '}| {p99:.3f} ms{(27 - len(f'{p99:.3f} ms')) * ' '}|\n")
        f.write("+---------------------------+---------------------------+---------------------------+\n")

if __name__ == "__main__":
    if len(sys.argv) != 3:
        print("Usage: python3 parse_and_average.py <input_tmp_file> <output_final_file>")
        sys.exit(1)

    input_file = sys.argv[1]
    output_file = sys.argv[2]

    results = parse_file(input_file)
    avg_result = average_results(results)
    write_output(avg_result, output_file)
